from numpy import array
import os.path
import pygame as pg
from PIL import Image, ImageSequence


def pg_gif_get(gif_path):
    gif = Image.open(gif_path)
    try:
        os.makedirs(gif_path[:-4])
        interval = []
        for i, frame in enumerate(ImageSequence.Iterator(gif)):
            interval.append(frame.info['duration'] / 60)
            frame.save(gif_path[:-4] + f'\\{i}.png')
    except FileExistsError:
        interval = []
        for frame in ImageSequence.Iterator(gif):
            interval.append(1000 / frame.info['duration'])
    return interval, gif_path[:-4]


def gif_to_images(gif_path):
    gif_frame = Image.open(gif_path)
    frames = [pg.image.fromstring(frame.convert('RGBA').tobytes(), frame.size, 'RGBA')
              for frame in ImageSequence.Iterator(gif_frame)]
    return frames


def gif_frames_number(gif_path):
    with Image.open(gif_path).convert('RGBA') as gif:
        return gif.n_frames


def image_array(image_path):
    with Image.open(image_path) as image:
        image = ImageSequence.Iterator(image)[0]
        return array(image)


